import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:orginone/components/CommandWidget/index.dart';
import 'package:orginone/dart/extension/index.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/utils/system/system_utils.dart';
import '../../../../dart/base/common/commands.dart';
import '../../../../dart/base/common/systemError.dart';
import '../../../../main.dart';
import '../../../../routers/router_const.dart';
import '../../../XButton/XButton.dart';
import '../../../XScaffold/XScaffold.dart';
import '../../../XText/XText.dart';

///异常页面列表
class ErrorListWidget extends StatelessWidget {
  const ErrorListWidget({Key? key}) : super(key: key);

  // 主视图
  Widget _buildView(BuildContext context) {
    SystemLog.err(kernel.statisticsInfo);
    List<LogInfo> errorArray = SystemLog.errors;
    // var t =
    //     DateUtil.formatDate(DateTime.now(), format: "yyyy-MM-dd HH:mm:ss.SSS");
    // errorArray.insert(0, {'t': t, 'errorText': kernel.statisticsInfo});
    return ListView.builder(
      scrollDirection: Axis.vertical,
      itemBuilder: (context, index) {
        var data = errorArray[index];

        return ListTile(
            title: XText.listTitle(data.title),
            subtitle: XText.listSubTitle(
              data.content,
              maxLines: 2,
            ) //Text(data['errorText']),
            ).height(60).onTap(() {
          RoutePages.to(
              context: context, child: ErrorSubPage(data.title, data.content));
        });
      },
      itemCount: errorArray.length,
    );
  }

  @override
  Widget build(BuildContext context) {
    return XScaffold(
      titleWidget: const XText.headerTitle("错误日志"),
      actions: [
        XButton.link(
          '清除日志',
          onPressed: () {
            SystemLog.clear();
            command.emitterFlag('error');
          },
        )
      ],
      // appBar: AppBar(
      //     title: const XText.headerTitle("错误日志"),
      //     actions: [
      //       XButton.link(
      //         '清除日志',
      //         onPressed: () {
      //           Storage.remove('work_page_error');
      //           command.emitterFlag('error');
      //         },
      //       )
      //     ]),
      body: SafeArea(
        child: CommandWidget(
          flag: "error",
          builder: (context, args) {
            return _buildView(context);
          },
        ),
      ),
    );
  }
}

class ErrorSubPage extends StatelessWidget {
  final String title;
  final String errInfo;

  const ErrorSubPage(this.title, this.errInfo, {Key? key}) : super(key: key);

  // 主视图
  Widget _buildView() {
    return <Widget>[Text(errInfo)].toColumn();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title ?? ''),
        actions: [
          // XButton.iconText(
          //   text: '复制',
          //   onPressed: () => SystemUtils.copyToClipboard(errInfo),
          // )
        ],
      ),
      body: Scrollbar(
          child: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: _buildView(),
      )),
    );
  }
}

mixin ErrorListenerMixin {
  late int successNum;
  late String path;
  late bool _isRunning = true;

  void init(BuildContext context) {
    path = RoutePages.routeData.currPageData.path ?? '';
    successNum = 0;
    // executeTask(context);
  }

  bool get hasError {
    return path == (RoutePages.routeData.currPageData.path ?? '') &&
        successNum == kernel.successReq;
  }

  bool get isRunning {
    if (path != (RoutePages.routeData.currPageData.path ?? '')) {
      _isRunning = false;
    }
    return _isRunning;
  }

  // 定义一个函数来执行任务并处理异常
  void executeTask(BuildContext context) async {
    try {
      // 检查是否需要停止
      if (!isRunning) {
        return;
      } else if (hasError) {
        _isRunning = false;
        RoutePages.to(context: context, path: Routers.errorGuide);
        return;
      } else {
        successNum = kernel.successReq;
      }

      // 使用Future.delayed来延迟下一次调用
      Future.delayed(const Duration(seconds: 3)).then((args) {
        executeTask(context);
      });
    } catch (e, s) {
      _isRunning = false;
      LogUtil.e('异常：$e 详情：$s');
    }
  }
}
